#include "ThresholderOtsuBleedThroughAware.hpp"

#include <ise/iseQuantificationThresholderOtsu1T.hpp>

ThresholderOtsuBleedThroughAware::ThresholderOtsuBleedThroughAware()
{}

int ThresholderOtsuBleedThroughAware::getVersoTreshold(const girl::tools::Image &verso)
{
    ise::GrayScaleHistogram h;
    h.reset(verso,0,0);
    ise::QuantificationThresholderOtsu otsu;
    std::vector<int> levels;
    otsu.getLevels(h,levels);
    _versoThreshold =  levels[0];
    return _versoThreshold;
}

int ThresholderOtsuBleedThroughAware::getRectoThreshold(const girl::tools::Image &recto,
                                                        const girl::tools::Image &verso)
{

    _versoThreshold = getVersoTreshold(verso);
    return getRectoThreshold(recto,verso,_versoThreshold);
}

int ThresholderOtsuBleedThroughAware::getRectoThreshold(const girl::tools::Image &recto,
                                                        const girl::tools::Image &verso, int versoThreshold)
{
    ise::HashHistogram h1;
    for(int i = 0; i< verso.width(); i++)
    {
        for(int j = 0; j< verso.height(); j++)
        {
            girl::tools::Pixel p = recto.getPixel(i,j);
            if(verso.getPixel(i,j).a() > versoThreshold)
                h1.addColor(p.a(),p.b(),p.c());
        }
    }

    ise::GrayScaleHistogram h(h1,0,0,255);
    ise::QuantificationThresholderOtsu otsu;
    std::vector<int> levels;
    otsu.getLevels(h,levels);
    _rectoThreshold =  std::min(levels[0],_versoThreshold);
    _versoThreshold = _rectoThreshold;
    return _rectoThreshold;

}
